import shoppingFn from './shop' //拿到购物车方法

let state = {
    buyArr: [],
    Checkout: null,
}

let mutations = {
    setBuyArr(state, val) {
        state.buyArr.push(
            {
                id: val.id,
                title: val.title,
                price: val.price,
                inventory: val.inventory,
                num: 1,
            }
        )
    },
    addNum(state, val) {
        state.buyArr.forEach((v) => {
            if (v.id == val.id) {  //id有值让购物车里的货品数量增加
                v.num++
            }
        })
    },
    successCheckout(state, data) {
        state.Checkout = data.msg
        state.buyArr = data.arr
    },
    faileCheckout(state, data) {
        state.Checkout = data.msg
        state.buyArr = data.arr
    },
    setEmpty(state, msg) {
        state.Checkout = msg
    }
}

let actions = {
    addProduct({ commit, state, dispatch }, val) {
        commit('setEmpty', null)
        let existId = state.buyArr.find(v => v.id == val.id) //判断id是否存在 find找到条件为true 的value值
        if (existId) {
            commit('addNum', val) //增加货品的数量
        } else {
            commit('setBuyArr', val) //增加货品
        }

        dispatch('shopping/reduceInventory', val, { root: true }) //每次点击是时候分发 减少商品
    },
    pay({ commit, state }) {
        // console.log(state)
        let ary = state.buyArr;
        shoppingFn.buyProducts(
            null,
            () => {
                commit('successCheckout', { arr: [], msg: '成功' })
            },
            () => {
                commit('faileCheckout', { arr: ary, msg: '失败' })
            }
        )
    }
}
let getters = {
    total(state) { //算价格
        let all = state.buyArr.map((v) => {
            return v.price * v.num
        })


        let num = 0
        all.map(v => {
            num += v
        })

        return num.toFixed(2)
    }
}

let car = {
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
}

export default car